package com.bh.web.controller.order;

import com.bh.common.enums.OrderStatus;
import com.bh.common.core.controller.BaseController;
import com.bh.common.core.domain.AjaxResult;
import com.bh.common.core.page.TableDataInfo;
import com.bh.common.utils.StringUtils;
import com.bh.common.utils.poi.ExcelUtil;
import com.bh.order.domain.JcLed;
import com.bh.order.service.IJcLedReceivingpartyService;
import com.bh.order.service.IJcLedService;
import com.bh.order.vo.JcLedCarryToShipVo;
import com.bh.order.vo.JcLedSignReceivingVo;
import com.bh.order.vo.JcLedSizeVo;
import com.bh.order.vo.JcLedVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/order/led")
public class JcLedController extends BaseController {

    @Autowired
    private IJcLedService jcLedService;
    @Autowired
    private IJcLedReceivingpartyService jcLedReceivingpartyService;

    /**
     * 查询可签收分段订单列表
     */
    @PreAuthorize("@ss.hasPermi('order:led:list')")
    @ApiOperation("查询分段订单列表")
    @GetMapping("/list")
    public TableDataInfo getLedList(JcLedVO queryVo) {
        startPage();
        List<JcLedVO> list = jcLedService.getJcLedList(queryVo);
        return getDataTable(list);
    }

    /**
     * 导出查询结果
     */
    @PreAuthorize("@ss.hasPermi('order:led:export')")
    @ApiOperation("导出分段订单列表")
    @PostMapping("/export")
    public void export(HttpServletResponse response, JcLedVO queryVo) {
        List<JcLedVO> list = jcLedService.getJcLedList(queryVo);
        ExcelUtil<JcLedVO> util = new ExcelUtil<>(JcLedVO.class);
        util.exportExcel(response, list, "分段订单数据");
    }

                       /**
     * 查询可签收分段订单列表
     */
                       @PreAuthorize("@ss.hasPermi('order:led:sign')")
    @ApiOperation("查询分段订单列表")
    @GetMapping("/listOrderQS")
    public TableDataInfo getOrderQS(JcLedVO queryVo) {
        startPage();
        List<JcLedVO> list = jcLedService.getOrderQS(queryVo);
        return getDataTable(list);
    }

    /**
     * 查询订单列表
     */
    @ApiOperation("查询在库订单列表")
    @PreAuthorize("@ss.hasPermi('order:led:inventory')")
    @GetMapping("/inventoryList")
    public TableDataInfo inventoryList(JcLedVO queryVo) {
        startPage();
        //会直接查询出发和到达的机构
        if (queryVo.getJcOrganizationId() == null) {
            queryVo.setJcOrganizationId(getOrgId());
        }
        List<JcLedVO> list = jcLedService.selectInventoryLedList(queryVo);
        return getDataTable(list);
    }


    /**
     * 查询分段订单列表
     */
    @ApiOperation("获取分段订单详细信息")
    @PreAuthorize("@ss.hasPermi('order:order:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(jcLedService.selectJcLedById(id));
    }


    /**
     * 派送员分段订单签收
     */
    @PreAuthorize("@ss.hasPermi('order:led:sign')")
    @ApiOperation("管理员分段订单签收")
    @PutMapping("/signReceiving")
    public AjaxResult signReceiving(@RequestBody JcLedSignReceivingVo signVo) {
        if (signVo.getLedIds() == null || signVo.getLedIds().length == 0) {
            signVo.setLedIds(new String[]{signVo.getLedId().toString()});
        }
        List<JcLed> jcLeds = jcLedService.listByIds(Arrays.asList(signVo.getLedIds()));
        if (jcLeds.isEmpty()) {
            return error("没有找到该分段订单");
        }
        jcLeds.forEach(jcLed -> {
            if (jcLed.getStatus() != OrderStatus.TRANSPORT_FINISHED.getValue() && jcLed.getStatus() != OrderStatus.READY_SEND.getValue()) {
                throw new RuntimeException("多个订单中存在未到达的订单，禁止进行批量签收！");
            }
        });
        // jcLeds 中的 jcOrderId 必须一致
        Set<Long> orderId = jcLeds.stream().map(JcLed::getJcOrderId).collect(Collectors.toSet());
        if (orderId.size() > 1) {
            return error("多个订单中存在不同的订单，禁止进行批量签收！");
        }

        if (StringUtils.isBlank(signVo.getUserId())) {
            signVo.setUserId(getUserId().toString());
        }
        return toAjax(jcLedService.signReceiving(signVo));
    }

    /**
     * 修改件重尺(主要针对拆分的单子)
     * getOrderLedger
     */
    @PreAuthorize("@ss.hasPermi('order:led:edit')")
    @ApiOperation("修改件重尺(主要针对拆分的单子)")
    @PostMapping(value = "/saveLedSize")
    public AjaxResult saveLedSize(@RequestBody JcLedSizeVo jcLedVO) {
        return toAjax(jcLedService.saveLedSize(jcLedVO));
    }


    /**
     * 自提签收（签收的是分段）
     */
    @PreAuthorize("@ss.hasPermi('order:led:self-sign')")
    @ApiOperation("自提签收（签收的是分段）")
    @PostMapping(value = "/setSelfPickSign")
    public AjaxResult setSelfPickSign(@RequestBody JcLedSignReceivingVo signVo) {
        if (signVo.getLedIds() == null || signVo.getLedIds().length == 0) {
            return error("分段订单ID不能为空");
        }
        if (signVo.getQsTime() == null) {
            return error("收货时间不能为空");
        }
        if (StringUtils.isBlank(signVo.getQsPerson())) {
            return error("签收人不能为空");
        }
        if (signVo.getQsTime() == null) {
            return error("签收时间不能为空");
        }
        return AjaxResult.success(jcLedService.setSelfPickSign(signVo));
    }

    /**
     * 配载到运单
     *
     * @param carryToShipVo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('order:led:carry-ship')")
    @PostMapping(value = "/carryToShip")
    public AjaxResult carryToShip(@RequestBody JcLedCarryToShipVo carryToShipVo) {
        return AjaxResult.success(jcLedService.carryToShip(carryToShipVo));
    }


    /**
     * 外包加载货品明细
     */
    @GetMapping("/getWbStowage/{shipmentId}")

    public TableDataInfo getWbStowage(@PathVariable("shipmentId") Long shipmentId) {
        startPage();
        return getDataTable(jcLedService.getWbStowageByShipmentId(shipmentId));
    }

    /**
     * 加载以被运单配载的表格
     */
    @GetMapping("/getStowage/{shipmentId}")
    public AjaxResult getStowage(@PathVariable("shipmentId") Long shipmentId) {
        return AjaxResult.success(jcLedService.getStowageByShipmentId(shipmentId));
    }

    /**
     * 加载未被 DISPATCH 运单配载的表格
     */
    @GetMapping("/getDispatchNotStowage")
    public AjaxResult getDispatchNotStowage() {
        return AjaxResult.success(jcLedService.getDispatchNotStowage());
    }

    /**
     * 加载被 DISPATCH 运单配载的表格
     */
    @PostMapping("/addDispatchOrder/{ledIds}")
    public AjaxResult addDispatchOrder(@PathVariable Long[] ledIds) {
        return AjaxResult.success(jcLedService.addDispatchOrder(ledIds));
    }


    /**
     * 加载被 DISPATCH 运单配载的表格
     */
    @GetMapping("/getDispatchStowage/{dispatchId}")
    public AjaxResult getDispatchStowage(@PathVariable Long dispatchId) {
        return AjaxResult.success(jcLedService.getDispatchStowage(dispatchId));
    }

   
    /**
     * 查询分段订单收发货方列表
     */
    @GetMapping("/getAddressInfo/{shipmentId}")
    public AjaxResult selectAddressInfo(@PathVariable("shipmentId") Long shipmentId) {
        return AjaxResult.success(jcLedReceivingpartyService.selectAddressInfo(shipmentId));
    }

    /**
     * 获取运单所配载的分段订单
     * @param shipmentId
     * @return
     */
    @GetMapping(value = "/getDZLedList/{shipmentId}")
    public AjaxResult getDZLedList(@PathVariable Long shipmentId) {
        List<JcLed> leds = jcLedService.getDZLedList(shipmentId);
        return AjaxResult.success(leds);
    }
}
